Popular Searches
Popular Course Categories
Popular Courses

Introduction to Java Servlets and Servlet API

Introduction to Java Servlets and Servlet API

Java Servlets and Servlet Life Cycle

Introduction to Java Servlets and Servlet API

Course: Advanced Java Training

Topic: Introduction to Java Servlets and Servlet API

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

JustAcademy Homepage: Visit JustAcademy


1. Introduction to Java Servlets

Java Servlets are server-side Java components used to process client requests and generate dynamic responses for web applications. They commonly handle HTTP requests from browsers, receive form data, interact with databases, manage application workflows, and return responses such as HTML, JSON, or plain text.

A servlet runs inside a servlet container, which is part of a web server or application server. The container manages the servlet lifecycle, maps incoming requests to the appropriate servlet, creates request and response objects, and provides services such as session management and security integration.

Servlets are an important foundation of Java web development. Technologies such as JavaServer Pages (JSP), Java web frameworks, and many enterprise web applications build on concepts introduced by the Servlet API.

2. Learning Objectives

  • Understand the purpose of Java Servlets.
  • Learn how client-server communication works in servlet-based applications.
  • Understand the Servlet API and its major interfaces and classes.
  • Explore the servlet lifecycle.
  • Learn how to handle HTTP GET and POST requests.
  • Understand request parameters, response content, and status codes.
  • Configure and deploy a basic servlet application.
  • Identify common servlet errors and development best practices.

3. What Is a Servlet?

A servlet is a Java class that follows the Servlet API contract and runs under the control of a servlet container. For HTTP applications, developers commonly extend the HttpServlet class and override methods such as doGet() and doPost().

Key Characteristics of Servlets

  • Server-side execution: Servlet code runs on the server rather than inside the user's browser.
  • Dynamic responses: Servlets can generate HTML, JSON, XML, and other response formats.
  • Platform independence: Java servlets can run on compatible Java runtimes and servlet containers.
  • Request processing: Servlets read request data, apply application logic, and produce responses.
  • Container-managed lifecycle: The servlet container controls initialization, request handling, and destruction.
  • Integration: Servlets can work with JDBC, business services, authentication mechanisms, and other Java components.

4. Understanding the Servlet API

The Servlet API defines interfaces and classes that allow Java applications to handle requests and responses in a web environment. It provides a standard contract between servlet code and the servlet container.

Modern Jakarta-based applications use the jakarta.servlet and jakarta.servlet.http packages. Older Java EE applications commonly use javax.servlet and javax.servlet.http. These package names are not interchangeable, so the imports must match the container and API version used by the project.

Important Servlet API Packages

Package Purpose Examples
jakarta.servlet Provides general servlet interfaces and classes. Servlet, ServletConfig, ServletContext, ServletRequest, ServletResponse
jakarta.servlet.http Provides HTTP-specific servlet functionality. HttpServlet, HttpServletRequest, HttpServletResponse, HttpSession
jakarta.servlet.annotation Provides annotations for servlet configuration and related features. WebServlet, WebFilter, WebListener

Version note: The examples in these notes use the Jakarta Servlet API with jakarta.servlet imports. If you use an older Tomcat or Java EE project that supports the javax.servlet API, use the matching package names and dependencies instead.

5. Servlet Architecture

A servlet-based web application follows the client-server model. The browser sends an HTTP request, the servlet container selects the target servlet, and the servlet processes the request and prepares a response.

Request-Response Flow

  1. The user enters a URL or submits a form in a browser.
  2. The browser sends an HTTP request to the web server.
  3. The servlet container examines the URL mapping and identifies the target servlet.
  4. The container creates or supplies the request and response objects.
  5. The container invokes the servlet's appropriate service method.
  6. The servlet reads request information and executes application logic.
  7. The servlet writes the response body and sets the appropriate status and headers.
  8. The container sends the HTTP response to the client.

Architecture Diagram

+-----------------------------+
|       Client Browser        |
+--------------+--------------+
               |
               | HTTP Request
               v
+-----------------------------+
| Web Server / Servlet        |
| Container                   |
+--------------+--------------+
               |
               | URL Mapping
               v
+-----------------------------+
|       Java Servlet          |
| doGet() / doPost()          |
+--------------+--------------+
               |
               | Business Logic
               v
+-----------------------------+
| Service / DAO / Database    |
+--------------+--------------+
               |
               | Result
               v
+-----------------------------+
| HTTP Response to Browser    |
+-----------------------------+

6. Servlet vs. Traditional Static Web Pages

Static Web Page Java Servlet
Usually serves content that has already been written into a file. Can generate a response dynamically at request time.
Does not normally execute Java business logic. Can execute Java application logic on the server.
Suitable for fixed informational content. Suitable for forms, data-driven pages, authentication flows, and APIs.
Does not directly manage application-specific database processing. Can call service and data-access components to retrieve or update data.

7. Important Interfaces and Classes in the Servlet API

7.1 Servlet Interface

The Servlet interface defines the basic lifecycle contract for servlet components. It includes methods for initialization, request processing, destruction, and retrieving servlet configuration information.

Important methods include:

  • init() — initializes the servlet.
  • service() — processes requests.
  • destroy() — allows cleanup before the servlet is taken out of service.
  • getServletConfig() — returns the servlet configuration object.
  • getServletInfo() — returns descriptive information about the servlet.

7.2 GenericServlet

GenericServlet is an abstract class that implements the general Servlet interface and provides a protocol-independent foundation for servlet development. HTTP applications generally use HttpServlet instead because it provides methods designed for HTTP requests.

7.3 HttpServlet

HttpServlet is the main class used to create HTTP-based servlets. It provides HTTP-specific request handling methods.

  • doGet() — handles HTTP GET requests.
  • doPost() — handles HTTP POST requests.
  • doPut() — handles HTTP PUT requests.
  • doDelete() — handles HTTP DELETE requests.
  • doHead() — handles HTTP HEAD requests.
  • doOptions() — handles HTTP OPTIONS requests.

7.4 HttpServletRequest

HttpServletRequest represents an HTTP request received by the servlet. It provides methods to read request parameters, headers, cookies, session information, and other request details.

Common methods include:

  • getParameter(String name) — reads a request parameter.
  • getParameterValues(String name) — reads multiple values for a parameter.
  • getMethod() — returns the HTTP method.
  • getRequestURI() — returns the request URI.
  • getHeader(String name) — reads a request header.
  • getSession() — obtains or creates an HTTP session.

7.5 HttpServletResponse

HttpServletResponse represents the HTTP response that the servlet sends to the client.

Common methods include:

  • setContentType(String type) — sets the response content type.
  • setStatus(int status) — sets the HTTP status code.
  • sendError(int status) — sends an error response.
  • sendRedirect(String location) — redirects the client to another URL.
  • getWriter() — obtains a character writer for the response body.
  • getOutputStream() — obtains a binary output stream.

7.6 ServletConfig

ServletConfig provides configuration information specific to one servlet, including its initialization parameters and access to the servlet context.

7.7 ServletContext

ServletContext represents the web application's shared context. It can provide access to application-level initialization parameters, resources, and attributes shared by components within the same web application.

7.8 HttpSession

HttpSession stores user-specific state across multiple HTTP requests. It is commonly used for login state, shopping carts, and temporary user workflow data. Sensitive session data should be protected, and sessions should be invalidated when no longer needed.

8. Understanding the Servlet Lifecycle

The servlet container manages the servlet lifecycle. A servlet typically moves through initialization, request processing, and destruction.

Lifecycle Stages

  1. Loading and instantiation: The container loads the servlet class and creates a servlet instance.
  2. Initialization: The container calls init() once for that servlet instance before it handles requests.
  3. Request processing: The container dispatches requests through service(), which routes HTTP requests to the relevant methods such as doGet() or doPost().
  4. Destruction: The container calls destroy() when the servlet is being taken out of service, allowing cleanup of resources.
  5. Garbage collection: After the servlet is no longer referenced, the JVM may reclaim its memory.

The container may initialize a servlet when it is first needed or during application startup, depending on configuration. The exact startup behavior depends on the container and servlet configuration.

9. Creating Your First Java Servlet

The following example uses Jakarta Servlet API and responds to HTTP GET requests with a simple HTML page.

WelcomeServlet.java

package com.example.web;

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {

    @Override
    protected void doGet(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");

        response.getWriter().println(
            "<!DOCTYPE html>" +
            "<html>" +
            "<head><title>Welcome</title></head>" +
            "<body>" +
            "<h1>Welcome to Java Servlets</h1>" +
            "<p>Your first servlet is working.</p>" +
            "</body></html>"
        );
    }
}

Explanation

  • @WebServlet("/welcome") maps the servlet to the /welcome URL path.
  • HttpServlet provides HTTP-specific request handling methods.
  • doGet() processes incoming GET requests.
  • HttpServletRequest provides information about the request.
  • HttpServletResponse is used to create the response.
  • setContentType() tells the browser that the response contains HTML encoded as UTF-8.

After deploying the application to a compatible servlet container, open http://localhost:8080/your-app-name/welcome, replacing your-app-name with the deployed application context path.

10. Handling HTTP GET Requests

The GET method is generally used to retrieve information. GET requests should not be used for actions that modify server-side state, such as deleting a record or transferring money.

Example: Displaying a Message

import java.io.IOException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/message")
public class MessageServlet extends HttpServlet {

    @Override
    protected void doGet(
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {

        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().println("This response was generated by a servlet.");
    }
}

When the browser requests /message, the servlet returns a plain-text response. GET requests can also contain query parameters, for example /message?name=Aarav.

11. Handling HTTP POST Requests

POST is commonly used to submit form data or send information that will be processed by the server. Using POST does not automatically make data secure; HTTPS, validation, authorization, and appropriate protections against cross-site request forgery (CSRF) may also be required.

HTML Form

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>User Form</title>
</head>
<body>
    <h2>Enter Your Details</h2>
    <form action="user" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>

        <button type="submit">Submit</button>
    </form>
</body>
</html>

UserServlet.java

import java.io.IOException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/user")
public class UserServlet extends HttpServlet {

    @Override
    protected void doPost(
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {

        request.setCharacterEncoding("UTF-8");

        String name = request.getParameter("name");

        response.setContentType("text/plain;charset=UTF-8");

        if (name == null || name.isBlank()) {
            response.sendError(
                HttpServletResponse.SC_BAD_REQUEST,
                "Name is required."
            );
            return;
        }

        response.getWriter().println("Form submitted successfully.");
    }
}

The servlet reads the submitted form parameter and validates that it is present. In a real application, validate the data according to business requirements, avoid displaying untrusted input without proper output encoding, and call an appropriate service layer to perform any required operation.

12. Request Parameters and HTTP Headers

Servlets can access information sent by clients through query strings, submitted forms, and HTTP headers.

Reading a Request Parameter

String username = request.getParameter("username");

Reading Multiple Parameter Values

String[] selectedSkills = request.getParameterValues("skills");

This is useful for form controls that allow multiple selections, such as checkboxes.

Reading an HTTP Header

String userAgent = request.getHeader("User-Agent");

Request parameters and headers originate from the client and should be treated as untrusted input. Validate them before using them in business logic, database queries, file operations, or security decisions.

13. Generating Different HTTP Responses

A servlet can set the response status, content type, headers, and body depending on the result of a request.

Setting a Status Code

response.setStatus(HttpServletResponse.SC_OK);

Sending a Not Found Response

response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource not found");

Redirecting the Client

response.sendRedirect("login.html");

A redirect instructs the client to make a new request to the specified location. Use appropriate status codes and avoid redirecting to untrusted URLs.

14. Servlet URL Mapping

URL mapping determines which servlet handles a particular request path. A mapping can be declared using the @WebServlet annotation or configured in a deployment descriptor such as web.xml.

Annotation-Based Mapping

@WebServlet("/products")
public class ProductServlet extends HttpServlet {
    // Request-handling methods
}

web.xml Mapping Example

<servlet>
    <servlet-name>ProductServlet</servlet-name>
    <servlet-class>com.example.web.ProductServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>ProductServlet</servlet-name>
    <url-pattern>/products</url-pattern>
</servlet-mapping>

Use the annotation-based approach for simple mappings or the deployment descriptor when centralized configuration is required. Avoid conflicting mappings for the same path unless the container configuration explicitly supports the intended behavior.

15. ServletConfig vs. ServletContext

Feature ServletConfig ServletContext
Scope Specific to an individual servlet. Shared across the web application.
Purpose Provides servlet-specific configuration. Provides application-wide information and shared attributes.
Initialization parameters Can expose parameters configured for a particular servlet. Can expose application-wide context parameters.
Typical use Configuring one servlet's behavior. Accessing application-level settings or shared resources.

16. Servlet Multithreading and Thread Safety

A servlet container may process multiple requests concurrently using the same servlet instance. Therefore, developers should avoid storing request-specific data in mutable instance fields.

Unsafe Example

public class UnsafeServlet extends HttpServlet {
    private String username;

    @Override
    protected void doGet(
            HttpServletRequest request,
            HttpServletResponse response) {
        username = request.getParameter("username");
        // Concurrent requests can overwrite this field.
    }
}

Safer Approach

public class SafeServlet extends HttpServlet {

    @Override
    protected void doGet(
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {

        String username = request.getParameter("username");
        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().println("Request received.");
    }
}

Use local variables for request-specific data and make shared components thread-safe. Avoid mutable servlet instance fields for data that belongs to an individual request.

17. Common Servlet Errors and Troubleshooting

Error or Problem Possible Cause Solution
HTTP 404 Not Found Incorrect URL, context path, or servlet mapping. Verify the deployed application name and URL pattern.
HTTP 405 Method Not Allowed The servlet does not handle the HTTP method used by the client. Implement the appropriate method, such as doPost(), where required.
Class not found Incorrect package name or missing application class. Check the package declaration, compiled output, and deployment structure.
Servlet API class not found Missing dependency or mismatch between API and container versions. Use the correct Servlet API dependency and compatible container.
HTTP 500 Internal Server Error An unhandled exception or server-side application failure. Inspect server logs and handle expected exceptions appropriately.
Request parameter is null Incorrect form field name or parameter not submitted. Check the HTML name attribute and request method.
Unexpected shared data between requests Mutable servlet fields used for request-specific information. Use local variables and thread-safe shared services.

18. Best Practices for Servlet Development

  • Use a compatible Servlet API and servlet container version.
  • Prefer HttpServlet for HTTP-based applications.
  • Keep request handling, business logic, and data-access logic in separate layers.
  • Validate all user input on the server.
  • Use parameterized SQL statements for database operations.
  • Set the response content type and character encoding correctly.
  • Use HTTPS to protect sensitive information in transit.
  • Avoid placing request-specific mutable data in servlet instance fields.
  • Handle exceptions without exposing internal stack traces or sensitive details to end users.
  • Use sessions carefully and apply appropriate authentication and authorization controls.
  • Keep database connections, files, and other resources managed with reliable cleanup patterns.
  • Use logging to support troubleshooting while protecting confidential information.

19. Mini Project: Student Information Servlet

Project Objective: Build a basic servlet application that accepts student details through a form and validates the submitted data.

Functional Requirements

  • Create an HTML form with fields for student name, email, and course.
  • Submit the form to a servlet using POST.
  • Read submitted values using HttpServletRequest.
  • Validate that required fields are present.
  • Return an appropriate success or validation response.
  • Extend the project by storing valid records in a database using JDBC.
  • Keep database logic in a separate repository or DAO class.

Suggested Project Structure

student-servlet-app/
├── src/
│   └── main/
│       ├── java/
│       │   └── com/example/
│       │       ├── web/
│       │       │   └── StudentServlet.java
│       │       ├── service/
│       │       │   └── StudentService.java
│       │       └── dao/
│       │           └── StudentDao.java
│       └── webapp/
│           └── student-form.html
└── pom.xml

Expected Learning Outcomes

After completing this project, learners should be able to map servlet URLs, process form submissions, validate request parameters, create HTTP responses, and organize a simple Java web application into separate layers.

20. Interview Questions and Answers

Q1. What is a Java Servlet?

A Java Servlet is a server-side Java component that processes client requests and generates responses within a servlet container.

Q2. What is the Servlet API?

The Servlet API defines the interfaces and classes that applications use to implement server-side request handling, response generation, lifecycle management, and related web features.

Q3. What is the role of a servlet container?

The container manages servlet lifecycle, request dispatching, URL mappings, and integration with web application services.

Q4. What is the difference between doGet() and doPost()?

doGet() commonly handles requests that retrieve resources, while doPost() commonly handles submitted data or operations that require request content.

Q5. What is HttpServletRequest?

It provides access to HTTP request information, including parameters, headers, request methods, and session information.

Q6. What is HttpServletResponse?

It allows the servlet to set status codes, headers, content types, and the response body sent to the client.

Q7. What is the servlet lifecycle?

The main lifecycle stages are initialization, request processing, and destruction, managed by the servlet container.

Q8. What is the difference between ServletConfig and ServletContext?

ServletConfig contains configuration specific to one servlet, whereas ServletContext represents the shared context of the web application.

Q9. What is HttpSession?

HttpSession allows an application to maintain user-specific state across multiple HTTP requests.

Q10. Why should servlet instance fields be used carefully?

Multiple requests may be processed concurrently using the same servlet instance. Mutable fields containing request-specific data can therefore cause race conditions and data leakage between requests.

Q11. What is URL mapping?

URL mapping connects a request path to a servlet. It can be configured with annotations such as @WebServlet or through web.xml.

Q12. What is the difference between javax.servlet and jakarta.servlet?

They are package namespaces associated with different generations of the Servlet API. The imports, dependency, and servlet container must be compatible with the same API generation.

21. Practice Exercises

  1. Create a servlet that returns a welcome message for a GET request.
  2. Build an HTML form and process it using a POST servlet.
  3. Read several request parameters and validate the submitted values.
  4. Return a 400 status for invalid input and a suitable success status for valid input.
  5. Create two servlets with different URL mappings.
  6. Compare servlet-specific configuration with application-wide context parameters.
  7. Build a simple student registration workflow.
  8. Connect a servlet to a database through a separate DAO class.
  9. Review a servlet for thread-safety issues and correct any mutable request-specific fields.

22. Quick Revision Checklist

  • Understand what Java Servlets do.
  • Know the role of the Servlet API and servlet container.
  • Recognize HttpServlet, HttpServletRequest, and HttpServletResponse.
  • Understand servlet initialization, request processing, and destruction.
  • Use doGet() and doPost() for appropriate HTTP operations.
  • Map URLs with @WebServlet or web.xml.
  • Read request parameters and generate responses correctly.
  • Use compatible jakarta.servlet or javax.servlet packages.
  • Validate client input and follow secure coding practices.
  • Keep servlet code thread-safe and separate business logic from request handling.

23. Official Documentation and Further Learning

24. Conclusion

Java Servlets are a fundamental technology for server-side Java web development. They allow applications to receive HTTP requests, validate input, execute application logic, interact with databases and services, and return dynamic responses.

Understanding the Servlet API, lifecycle, request and response objects, URL mapping, HTTP methods, and thread-safety principles provides a strong foundation for learning JSP, filters, session management, JDBC integration, and Java web frameworks.

To continue learning enterprise Java development, explore the Advanced Java Training Course at JustAcademy, register for a course demo, or visit the JustAcademy Homepage.

Previous Next
whatsapp